package com.sduonline.isdapp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.sduonline.isdapp.model.Image;

public class ImageDao {

	private static ConnectionPool pool;

	public ImageDao() {
		if (pool == null) {
			pool = ConnectionPool.getInstance();
		}
	}

	public boolean saveBatch(List<Image> images) {
		Connection conn = pool.getConnection();
		String sql = "insert into isd_image(articleId,link,baseUrl) values(?,?,?)";
		PreparedStatement ptmt = null;

		try {
			conn.setAutoCommit(false);
			ptmt = conn.prepareStatement(sql);

			for (Image img : images) {
				ptmt.setInt(1, img.getArticleId());
				ptmt.setString(2, img.getLink());
				ptmt.setString(3, img.getBaseUrl());

				ptmt.addBatch();
			}

			ptmt.executeBatch();
			ptmt.close();
			conn.commit();
			conn.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return false;
			}
			return false;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

	public boolean saveOrUpdateBatch(List<Image> images) {
		Connection conn = pool.getConnection();
		String sql = "insert into isd_image(articleId,link,baseUrl) values(?,?,?) on duplicate key update articleId=?,link=?,baseUrl=? ";
		PreparedStatement ptmt = null;

		try {
			conn.setAutoCommit(false);

			ptmt = conn.prepareStatement(sql);

			for (Image img : images) {
				ptmt.setInt(1, img.getArticleId());
				ptmt.setString(2, img.getLink());
				ptmt.setString(3, img.getBaseUrl());
				ptmt.setInt(4, img.getArticleId());
				ptmt.setString(5, img.getLink());
				ptmt.setString(6, img.getBaseUrl());

				ptmt.addBatch();
			}
			ptmt.executeBatch();
			conn.commit();
			ptmt.close();
			conn.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return false;
			}
			return false;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

}
